<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">扣货</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('扣货表')">导出</a-button>
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <!-- 高级查询区域 -->
<!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
<!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--        <a-menu slot="overlay">-->
<!--          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>-->
<!--        </a-menu>-->
<!--        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
<!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div>
        <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row>
          <a-space>
            <a-form-item label="仓库">
              <j-dict-select-tag style="width: 200px"  type="list" v-model="queryParam.warehouseCode"
                                 dictCode="erp_warehouse,name,code" placeholder="请选择仓库" />
            </a-form-item>
            <a-form-item label="起始日期">
              <a-date-picker type="ge" v-model="queryParam.createTime_begin" :format="dateFormat" :valueFormat="dateFormat" @change="changeDateBegin"/>
            </a-form-item>
            <a-form-item label="截至日期">
              <a-date-picker type="le" v-model="queryParam.createTime_end" :format="dateFormat" :valueFormat="dateFormat" @change="changeDateEnd"/>
            </a-form-item>
          </a-space>
        </a-row>
        </a-form>
      </div>

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:'radio'}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow='rowProperties'
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <buss-deduct-goods-modal ref="modalForm" @ok="modalFormOk"></buss-deduct-goods-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BussDeductGoodsModal from './modules/BussDeductGoodsModal'
  import moment from 'dayjs'
  import { getAction, putAction } from '@api/manage'

  export default {
    name: 'BussDeductGoodsList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      BussDeductGoodsModal
    },
    data () {
      return {
        description: '扣货表管理页面',
        dateFormat: 'YYYY-MM-DD',
        moment,
        disableMixinCreated: true,
        queryParam: {
          warehouseCode: '',
          createTime_begin: '',
          createTime_end: ''
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'入库单',
            align:"center",
            dataIndex: 'code'
          },
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'物料名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'spec'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'meUnit_dictText'
          },
          {
            title:'数量',
            align:"center",
            dataIndex: 'quantity'
          },
          {
            title:'扣货数量',
            align:"center",
            dataIndex: 'occupationQuantity'
          },
          {
            title:'辅助单位',
            align:"center",
            dataIndex: 'fff'
          },
          {
            title:'辅助数量',
            align:"center",
            dataIndex: 'sss'
          },
          {
            title:'库位',
            align:"center",
            dataIndex: 'warehouseLocation_dictText'
          },
          {
            title:'批次号',
            align:"center",
            dataIndex: 'batch'
          },
          {
            title:'物料批号',
            align:"center",
            dataIndex: 'materialBatchNumber'
          },
          {
            title:'制单人',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'制单日期',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title:'质检状态',
            align:"center",
            dataIndex: 'qualityInspectionStatus_dictText'
          },
          {
            title:'当前状态',
            align:"center",
            dataIndex: 'deductStatus_dictText',
            customRender:function (text,record,index) {
              if(!text){
                return record.deductStatus
              }
              return text
            }
          },

          // {
          //   title:'扣货原因',
          //   align:"center",
          //   dataIndex: 'remark'
          // },
          // {
          //   title:'库存明细id',
          //   align:"center",
          //   dataIndex: 'inventoryDetails'
          // },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   align:"center",
          //   fixed:"right",
          //   width:147,
          //   scopedSlots: { customRender: 'action' }
          // }
        ],
        url: {
          list: "/detail/bussInventoryDetails/deduct/list",
          delete: "/org.jeecg.modules.business/bussDeductGoods/delete",
          deleteBatch: "/org.jeecg.modules.business/bussDeductGoods/deleteBatch",
          exportXlsUrl: "/detail/bussInventoryDetails/deduct/exportXls",
          importExcelUrl: "detail/bussInventoryDetails/deduct/exportXls",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.queryParam.createTime_begin = moment().subtract(30, 'days').format(this.dateFormat)
      this.queryParam.createTime_end = moment().format(this.dateFormat)
      this.getSuperFieldList();
      // this.loadData();
    },
    watch: {
      // queryParam: {
      //   handler(newValue, oldValue) {
      //     console.log('旧的值：',oldValue)
      //     this.loadData();
      //   },
      //   deep: true // 监听对象的深层变化
      // }
      'queryParam.warehouseCode'(newName, oldName) {
        // console.log('User name changed from', oldName, 'to', newName);
        this.loadData();
      },
      'queryParam.createTime_begin'(newName, oldName) {
        console.log(oldName)
        // console.log('User name changed from', oldName, 'to', newName);
        this.loadData();
      },
      'queryParam.createTime_end'(newName, oldName) {
        // console.log('User name changed from', oldName, 'to', newName);
        this.loadData();
      },
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        console.log('huoqu:',this.queryParam.createTime_begin)
        if(this.queryParam.warehouseCode && this.queryParam.createTime_begin && this.queryParam.createTime_end){
          params.warehouseCode = this.queryParam.warehouseCode
          params.createTime_begin = this.queryParam.createTime_begin
          params.createTime_end = this.queryParam.createTime_end
        }else {
          return;
        }
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result;
            this.dataSourceBack=this.dataSource
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleAdd: function () {
        console.log(this.selectionRows)
        if(this.selectionRows.length == 0){
          this.$message.error("请选择扣货物料")
          return;
        }
        let record = this.selectionRows[0]
        console.log(record)
        if(record.qualityInspectionStatus == 2){
          this.$message.error("不合格无法扣货")
          return;
        }
        let detail = {}
        detail.inventoryDetailId =  record.id
        detail.materialCode = record.materialCode
        detail.materialId = record.materialId
        detail.materialName = record.materialName
        detail.meUnit_dictText = record.meUnit_dictText
        detail.spec = record.spec
        detail.num = record.quantity
        this.$refs.modalForm.edit(detail);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
        // this.$refs.modalForm.add();
        // this.$refs.modalForm.title = "新增";
        // this.$refs.modalForm.disableSubmit = false;
      },

      rowProperties(record, index) {
        return {
          on:{
            click: (event)=>{
              this.selectedRowKeys = [record.id]
              this.selectedRowKey = record.id
              this.selectionRows = [record]
              // this.$nextTick(() => {
              //   const rows = this.$refs.table.$el.querySelectorAll('tr'); // 获取所有的 tr 元素
              //   rows.forEach(row => {
              //     // 动态删除 tr 元素的类名
              //     row.classList.remove('ant-table-row-selected');
              //   });
              // });
            }
          }
          // onClick: (event) => {
          //   alert(888888)
          // },
        }
      },
      changeDateBegin(arg) {
        this.$set(this.queryParam ,'createTime_begin',arg)
      },
      changeDateEnd(arg) {
        this.$set(this.queryParam ,'createTime_end',arg)
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'BigDecimal',value:'num',text:'扣货数量',dictCode:''})
        fieldList.push({type:'string',value:'remark',text:'扣货原因',dictCode:''})
        fieldList.push({type:'string',value:'inventoryDetails',text:'库存明细id',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>